<script setup>
import { Message } from "@arco-design/web-vue";
import { IconEdit, IconPlus } from "@arco-design/web-vue/es/icon";
import axios from "axios";
import { ref } from "vue";
const file = ref();
const baseUrl = import.meta.env.VITE_API_BASE_URL;

let props = defineProps({
  action: "",
  name: "file",
  uploadData: {},
  draggable: false,
  showFileList: false,
  accept: ""
});

const uploadErrorList = defineModel('uploadErrorList', { type: Array, default: [] })


const onSuccess = () => {
  Message.success("导入成功");
};

const onChange = (_, currentFile) => {
  file.value = {
    ...currentFile,
  };
};
const onProgress = (currentFile) => {
  file.value = currentFile;
};

const customRequest = (option) => {
  const { onProgress, onError, onSuccess, fileItem, name } = option;
  const formData = new FormData();
  formData.append(name || 'file', fileItem.file);
  if (props.uploadData) {
    Object.keys(props.uploadData).forEach(key => {
      formData.append(key, props.uploadData[key]);
    });
  }
  let actionUrl = baseUrl + props.action;
  axios.post(actionUrl, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }).then(res => {
    if (res.data.code != 200) {
      // Message.error(res.data.msg);
      if (res.data.msg) {
        let errorList = res.data.msg.split(",");
        uploadErrorList.value = errorList;
      }
      onError(res.data.msg);
    } else {
      onSuccess(res);
    }
  }).catch(err => {
    onError(err);
  })
}

</script>

<template>
  <a-upload :custom-request="customRequest" :limit="1" :show-upload-button="true" :name="name" :data="uploadData"
    :draggable="draggable" :showFileList="showFileList" :accept="accept" @change="onChange" @progress="onProgress"
    @success="onSuccess">
  </a-upload>

</template>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
